package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"time"
	"zuoye_2/cache"
	"zuoye_2/models"
)

type LoController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *LoController) Add() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	home := c.GetString("home")
	tel := c.GetString("tel")
	docker := c.GetString("docker")
	car := c.GetString("car")
	loo := models.Lo{
		Model:  gorm.Model{},
		Id:     id,
		Name:   name,
		Home:   home,
		Tel:    tel,
		Docker: docker,
		Car:    car,
	}
	err := models.DB.Create(&loo).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *LoController) List() {
	var li []models.Lo
	err := models.DB.Find(&li).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := fmt.Sprintf("lo_list_%d", models.Lo{}.Id)
		res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
		if res != "" {
			json.Unmarshal([]byte(res), li)
		} else {
			rest, _ := json.Marshal(li)
			cache.Rdb.Set(cache.Ctx, key, rest, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: li,
		}
		c.ServeJSON()
		return
	}

}
func (c *LoController) Detail() {
	id, _ := c.GetInt("id")
	var lo []models.Lo
	err := models.DB.Debug().Where("id=?", id).First(&lo).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "详情查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := fmt.Sprintf("lo_detail_%d", models.Lo{}.Id)
		res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
		if res != "" {
			json.Unmarshal([]byte(res), lo)
		} else {
			rest, _ := json.Marshal(lo)
			cache.Rdb.Set(cache.Ctx, key, rest, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "详情查询成功",
			Data: lo,
		}
		c.ServeJSON()
		return
	}
}
